﻿using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Basefr.Runtime.Helpers
{
    public static class QrCodeHelper
    {
        public static byte[] CreateQrCodeBytes(string data)
        {
            var generator = new QRCodeGenerator();
            var qrCodeData = generator.CreateQrCode(data, QRCodeGenerator.ECCLevel.L);
            var qrCode = new QRCode(qrCodeData);
            var bitMap = qrCode.GetGraphic(20) as Bitmap;

            var stream = new MemoryStream();

            bitMap.Save(stream, ImageFormat.Png);

            return stream.ToArray();
        }

        public static void CreateQrCodeAndSavePngFile(string data, string fileFullName)
        {
            var generator = new QRCodeGenerator();
            var qrCodeData = generator.CreateQrCode(data, QRCodeGenerator.ECCLevel.L);
            var qrCode = new QRCode(qrCodeData);
            var bitMap = qrCode.GetGraphic(20) as Bitmap;

            var file = new FileInfo(fileFullName);

            if (string.IsNullOrWhiteSpace(file.DirectoryName))
            {
                throw new ApplicationException("指定的二维码图片文件目录无效");
            }

            if (!Directory.Exists(file.DirectoryName))
            {
                Directory.CreateDirectory(file.DirectoryName);
            }

            bitMap.Save(fileFullName, ImageFormat.Png);
        }
    }
}
